import React, { useState, useEffect } from 'react';
import { Table, Button, Modal, Form, Input, message, Select, Pagination } from 'antd';
import { PlusOutlined, EditOutlined, CheckOutlined, CloseOutlined } from '@ant-design/icons';

const { Option } = Select;
const { Search } = Input;

const WebApplicationPage = () => {
    const [data, setData] = useState([]);
    const [loading, setLoading] = useState(false);
    const [editVisible, setEditVisible] = useState(false);
    const [createFormVisible, setCreateFormVisible] = useState(false);
    const [selectedRecord, setSelectedRecord] = useState(null);
    const [searchStatus, setSearchStatus] = useState('');
    const [currentPage, setCurrentPage] = useState(1);
    const [pageSize, setPageSize] = useState(10);
    const [total, setTotal] = useState(0);
    const [form] = Form.useForm();

    useEffect(() => {
        fetchData();
    }, [searchStatus, currentPage, pageSize]);

    const fetchData = async () => {
        setLoading(true);
        try {
            const response = await fetch(`${API_URL}/webApp/search`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    status: searchStatus,
                    current: currentPage,
                    pageSize: pageSize
                })
            });
            const result = await response.json();
            if (result.code === 0) {
                setData(result.data.content);
                setTotal(result.data.totalElements);
            } else {
                message.error('获取数据失败');
            }
        } catch (error) {
            message.error('请求出错');
        } finally {
            setLoading(false);
        }
    };

    const handleCreate = () => {
        setCreateFormVisible(true);
    };

    const handleEdit = (record) => {
        setSelectedRecord(record);
        setEditVisible(true);
        form.setFieldsValue({
            name: record.name,
            desc: record.descr,
            code: record.code
        });
    };

     const handleCreateSubmit = async (values) => {
        try {
            const response = await fetch(`${API_URL}/webApp/create`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    name: values.name,
                    desc: values.desc,
                    code: values.code
                })
            });
            const result = await response.json();
            if (result.code === 0) {
                message.success('创建成功');
                setCreateFormVisible(false);
                fetchData();
            } else {
                message.error('创建失败');
            }
        } catch (error) {
            message.error('请求出错');
        }
    };

    const handleUpdateSubmit = async (values) => {
        try {
            const response = await fetch(`${API_URL}/webApp/update`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    id: selectedRecord.id,
                    name: values.name,
                    desc: values.desc,
                    code: values.code
                })
            });
            const result = await response.json();
            if (result.code === 0) {
                message.success('更新成功');
                setEditVisible(false);
                fetchData();
            } else {
                message.error('更新失败');
            }
        } catch (error) {
            message.error('请求出错');
        }
    };


    const handleCancel = () => {
        setEditVisible(false);
        setCreateFormVisible(false);
        form.resetFields();
    };

    const handleSearchStatusChange = (value) => {
        setSearchStatus(value); // 设置状态搜索值
    };

    const handleSearch = () => {
        fetchData(); // 执行搜索
    };

    const handlePaginationChange = (page, pageSize) => {
        setCurrentPage(page);
        setPageSize(pageSize);
    };

    return (
      <div>
        <div style={{display: 'flex', justifyContent: 'center', marginBottom: 16}}>
          <Select
            value={searchStatus}
            onChange={handleSearchStatusChange}
            style={{width: 150, marginRight: 16}}
          >
            <Option value="">全部</Option>
            <Option value="ENABLED">启用</Option>
            <Option value="DISABLED">禁用</Option>
          </Select>
          <Search
            placeholder="请输入搜索内容"
            enterButton="搜索"
            size="large"
            onSearch={handleSearch}
            style={{flex: 1}}
          />
        </div>
        <Table
          dataSource={data}
          loading={loading}
          columns={[
            {
              title: '名称',
              dataIndex: 'name',
              key: 'name',
            },
            {
              title: '编码',
              dataIndex: 'code',
              key: 'code',
            },
            {
              title: '描述',
              dataIndex: 'descr',
              key: 'descr',
            },
            {
              title: '状态',
              dataIndex: 'status',
              key: 'status',
              render: status => <span>{status.desc}</span>,
            },
            {
              title: '操作',
              key: 'action',
              render: (text, record) => (
                <>
                  <a href={`/welcome?appId=${record.id}`}> 编辑 </a>
                </>
              ),
            },
          ]}
          pagination={false} // 禁用内置分页
        />
        <Pagination
          current={currentPage}
          pageSize={pageSize}
          total={total}
          onChange={handlePaginationChange}
          style={{marginTop: 16}}
        />
      </div>
    );
};

export default WebApplicationPage;
